//
//  IGHistoryList.m
//  iGameApp
//
//  Created by lanou on 16/1/20.
//  Copyright © 2016年 WYC. All rights reserved.
//

#import "IGHistoryList.h"

@interface IGHistoryList ()

@property (nonatomic, strong) NSManagedObjectContext *context;

@end

@implementation IGHistoryList

+ (IGHistoryList *)defaultIGHistoryList
{
    static IGHistoryList *historyList = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        historyList = [[IGHistoryList alloc] init];
    });
   
    return historyList;
}

- (void)saveDataAtLoacllyWithTitle:(NSString *)title img:(NSString *)img vid:(NSString *)vid
{
    NSMutableArray *histArray = [self searchLocationData];
    
    for (HistoryList *list in histArray) {
        if ([list.vid isEqualToString:vid]) {
            [_context deleteObject:list];
        }
    }
    HistoryList *historyModel = [NSEntityDescription insertNewObjectForEntityForName:@"HistoryList" inManagedObjectContext:_context];
    historyModel.vid = vid;
    historyModel.titleName = title;
    historyModel.imgUrlString = img;
    [_context save:nil];
}

- (NSMutableArray *)searchLocationData
{
    if (_context == nil) {
        AppDelegate *delegate = [UIApplication sharedApplication].delegate;
        _context = delegate.managedObjectContext;
    }
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"HistoryList" inManagedObjectContext:_context];
    [fetchRequest setEntity:entity];
    NSError *error = nil;
    NSArray *fetchedObjects = [_context executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"失败");
    }
    
    NSMutableArray *historyArray = [NSMutableArray array];
    for (NSInteger i = (fetchedObjects.count - 1); i >= 0; i--) {
        [historyArray addObject:fetchedObjects[i]];
    }
    return historyArray;
}

- (void)removeAllHistoryList
{
    NSMutableArray *histArray = [self searchLocationData];
    for (HistoryList *list in histArray) {
        [_context deleteObject:list];
    }
    [_context save:nil];
}


@end
